import router from './router';
import { useAppStore } from '@/stores/index';
import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css';
import { isPathMatch } from './utils';

import { getToken } from '@/utils/auth';
import { isEmpty } from 'es-toolkit/compat';

NProgress.configure({ showSpinner: false });

router.beforeEach(async (to, _from, next) => {
  NProgress.start();
  if (getToken() && !isPathMatch('/login', to.path)) {
    const appStore = useAppStore();
    if (appStore.$state.menuFromServer && isEmpty(appStore.$state.serverMenu)) {
      await appStore.fetchServerMenuConfig();

      // if (isEmpty(appStore.$state.serverMenu)) {
      //   next(`/login?redirect=${to.fullPath}`);
      // } else {
        next({ ...to, replace: true });
      // }
    } else {
      next();
    }
  } else {
    if (isPathMatch('/login', to.path)) {
      // 在免登录白名单，直接进入
      next();
    } else {
      next(`/login?redirect=${to.fullPath}`);
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});
